import json

from Crypto.Cipher import AES
from Crypto.Util.Padding import pad, unpad
from Crypto.Random import get_random_bytes
import base64


# AES CBC 加密函数
def aes_cbc_encrypt(data, key, iv):
    # 确保数据是字节类型
    if isinstance(data, str):
        data = data.encode('utf-8')

    # 创建 AES cipher 对象
    cipher = AES.new(key, AES.MODE_CBC, iv)

    # 填充数据至16字节倍数
    padded_data = pad(data, AES.block_size)

    # 执行加密
    ciphertext = cipher.encrypt(padded_data)
    print(ciphertext.hex())

    # 返回加密后的数据，以Base64编码
    return base64.b64encode(ciphertext).decode('utf-8')


# AES CBC 解密函数
def aes_cbc_decrypt(ciphertext, key, iv):
    # 解码 Base64 密文
    ciphertext = base64.b64decode(ciphertext)

    # 创建 AES cipher 对象
    cipher = AES.new(key, AES.MODE_CBC, iv)

    # 执行解密
    decrypted_data = cipher.decrypt(ciphertext)

    # 去除填充
    return unpad(decrypted_data, AES.block_size).decode('utf-8')


# # 示例用法
# if __name__ == "__main__":
#     key = b"lUhIC6cYFVCTCGRdgdNK4nC1hAFORjZg"  # 16字节的密钥
#     iv = b"DTsVbqw8xd4QRWOB"  # 16字节的IV
#
#     data = {"device":{"app_version":"10.15.0","device_external_code":"VLgIqewFr4HYa0zoP8vAachmqMI5_0QlDAedc8s1oZbPuNwhc81ces8WesV_Le3291CvUUbm2inxEDIfRfbWE5kvvAkFnHZKQIc2_PnkgFFtn2rrR5LkKSG2_jweF-Ard4FTirYfs1RkhVawzqiR41CqdsHb0er_","id":"fd478b316c854ba090bc61801b0ea452","language":"zh","latitude":"36.661696","longitude":"117.072313","manufacturer":"Google","model":"Pixel 3","os_name":"Android","os_version":"10","timezone":"Asia/Shanghai","user_agent":"Android com.starbucks.cn.baselib/10.15.0 (Pixel 3; 10)"},"password":"123456","userName":"17812345678"}
#     encrypted_data = aes_cbc_encrypt(json.dumps(data,ensure_ascii=False,separators=(",",":")), key, iv)
#     print(f"Encrypted: {encrypted_data}")
#
#     decrypted_data = aes_cbc_decrypt(encrypted_data, key, iv)
#     print(f"Decrypted: {decrypted_data}")
